package com.conjane.algo.array_list;

/**
 * 翻转整数
 */
public class ReverseInteger {

    private static int reverse(int x) {
        // 如果数值大于等于最大值或者小于最小值，则返回0
        if (x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE) {
            return 0;
        }
        // 根据数值得到正负号，数值都当做整数翻转，最后再乘以翻转后的数值
        int sign = x < 0 ? -1 : 1;
        x = x < 0 ? -x : x;
        /**
         * 数值转化成字符串，再转成字符数组，逆序遍历数组，放入到新的数组中
         * 数组再转成字符串，字符串转成整数，最后乘以正负号
         */
        String s = String.valueOf(x);
        char[] srcChars = s.toCharArray();
        char[] desChars = new char[srcChars.length];
        for (int i = 0; i < srcChars.length; i++) {
            desChars[i] = srcChars[srcChars.length - 1 - i];
        }
        String desValueStr = String.valueOf(desChars);
        long desValue = Long.parseLong(desValueStr);
        return desValue * sign >= Integer.MAX_VALUE || desValue * sign <= Integer.MIN_VALUE ? 0 : (int) (desValue * sign);
    }

    private static int reversePlus(int x){
        // 如果数值大于等于最大值或者小于最小值，则返回0
        if (x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE) {
            return 0;
        }
        // 根据数值得到正负号，数值都当做整数翻转，最后再乘以翻转后的数值
        int sign = x < 0 ? -1 : 1;
        x = x < 0 ? -x : x;
        String s = String.valueOf(x);
        char[] desChars = s.toCharArray();
        // 做首位互换
        for (int i = 0; i < desChars.length / 2; i++) {
            char temp;
            temp = desChars[i];
            desChars[i] = desChars[desChars.length - 1 - i];
            desChars[desChars.length - 1 - i] = temp;
        }
        String desValueStr = String.valueOf(desChars);
        long desValue = Long.parseLong(desValueStr);
        return desValue * sign >= Integer.MAX_VALUE || desValue * sign <= Integer.MIN_VALUE ? 0 : (int) (desValue * sign);
    }

    private static int reversePlusPlus(int x){
        // 如果数值大于等于最大值或者小于最小值，则返回0
        if (x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE) {
            return 0;
        }
        // 根据数值得到正负号，数值都当做整数翻转，最后再乘以翻转后的数值
        int sign = x < 0 ? -1 : 1;
        x = x < 0 ? -x : x;
        /**
         * 数值转化成字符串，再转成字符数组，逆序遍历数组，放入到新的数组中
         * 数组再转成字符串，字符串转成整数，最后乘以正负号
         */
        String s = String.valueOf(x);
        char[] srcChars = s.toCharArray();
        long sum = 0;
        for (int i = 0; i < srcChars.length; i++) {
            long value = srcChars[i] - '0';
            long pow = (long)Math.pow(10, i);
            sum = value * pow + sum;
        }
        return sum * sign >= Integer.MAX_VALUE || sum * sign <= Integer.MIN_VALUE ? 0 : (int)(sum * sign);
    }

    public static void main(String[] args) {
        int[] array = new int[]{120, -200, 485, -120, Integer.MIN_VALUE, Integer.MAX_VALUE,1147483647};
        for (int i = 0; i < array.length; i++) {
            int reverse = reversePlusPlus(array[i]);
            System.out.println(array[i] + "<=======>" + reverse);
        }
    }
}
